<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Cities;
use App\Models\FileUpload;
use App\Models\FilmTypeMaster;
use App\Models\MacroManagement;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\NewPrecut;
use App\Models\PartMaster;
use App\Models\Precut;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\RollMaster;
use App\Models\Warranty;
use App\Models\WarrantyLogs;
use App\Models\WarrantyMsg;
use App\Models\WarrantyToVehicleCoverage;
use App\Services\ModuleService;
use App\Services\UploadService;
use App\Services\UserService;
use App\Services\WarrantyService;
use App\User;
use Encore\Admin\Grid\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use OSS\Http\RequestCore;
use phpDocumentor\Reflection\Types\False_;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class WarrantyController extends Controller
{
    private $moduleService;

    public function __construct(ModuleService $moduleService)
    {
        $this->moduleService = new ModuleService();
    }

    public function index(Request $request)
    {
        Refresh();
        $page = [
            'page_name' => 'warranty',
            'title' => ts('MANAGEWARRANTY'),
        ];
        $user_id = session('admin.id');
        $user_level = session('admin.user_type');
        $notice_type = $request->input('notice_type') ?: '';
        $ids = $request->input('ids') ?: '';
        $menus = $this->moduleService->getWebButton(session('admin.role_id') ?? 0, $request->path());
        $db = DB::table('warranty', 'w')
            ->whereNull('w.deleted_at')
            ->leftJoin('users as u', 'w.user_id', '=', 'u.id')
            ->leftJoin('warranty_to_vehicle_coverage as wvc', 'w.id', '=', 'wvc.warranty_id')
            ->leftJoin('new_precut as p', 'w.precut_id', '=', 'p.id')
            ->leftJoin('film_type_master as fm', 'fm.id', 'wvc.film_type_id');
        if (!empty($notice_type)) {
            $db = $db->join('warranty_notice as wn', 'wn.warranty_id', 'w.id');
        }

        $db = $db
            ->whereNull('wvc.deleted_at')
            ->groupBy('w.id');

        /*if ($user_level == 2) {
            $db = $db->where(function ($query) use ($user_id) {
                $query->orWhere('u.id', $user_id)
                    ->orWhere('u.creator_id', $user_id)
                    ->orWhere(function ($q2) use ($user_id) {
                        $q2->where('w.user_id', 0)
                            ->where('w.created_by', $user_id);
                    });
            });
        }*/
        // 根据是否通过判断，假如通过则
        if ($user_level == 2) {
            $db = $db->where(function ($query) use ($user_id) {
                $query->where(function ($q1) use ($user_id) {
                    $q1->where('w.distributor_id', $user_id)
                        ->where('w.approved', 1);
                })
                    ->orWhere(function ($q2) use ($user_id) {
                        $q2->where('w.approved', '!=', 1)
                            ->where(function ($q3) use ($user_id) {
                                $q3->where([
                                    'w.user_id' => 0,
                                    'w.created_by' => $user_id
                                ])
                                    ->orWhere('u.id', $user_id)
                                    ->orWhere('u.creator_id', $user_id);
                            });
                    });
            });
        }

        if ($user_level == 4) {
            $dist_user_id = (new UserService())->getDistributions($user_level, $user_id);
            if (empty($dist_user_id)) {
                $db = $db->where(function ($query) use ($user_id) {
                    $query->where(function ($q1) use ($user_id) {
                        $q1->where('w.distributor_id', $user_id)
                            ->where('w.approved', 1);
                    })
                        ->orWhere(function ($q2) use ($user_id) {
                            $q2->where('w.approved', '!=', 1)
                                ->where(function ($q3) use ($user_id) {
                                    $q3->where([
                                        'w.user_id' => 0,
                                        'w.created_by' => $user_id
                                    ])
                                        ->orWhere('u.id', $user_id)
                                        ->orWhere('u.creator_id', $user_id);
                                });
                        });
                });
            } else {
                $db = $db->where(function ($query) use ($dist_user_id, $user_id) {
                    $query->where(function ($q1) use ($dist_user_id, $user_id) {
                        $q1->whereIn('w.distributor_id', $dist_user_id)
                            ->where('w.approved', 1);
                    })
                        ->orWhere(function ($q2) use ($dist_user_id, $user_id) {
                            $q2->where('w.approved', '!=', 1)
                                ->where(function ($q3) use ($dist_user_id, $user_id) {
                                    $q3->where([
                                        'w.user_id' => 0,
                                        'w.created_by' => $user_id
                                    ])
                                        ->orWhereIn('u.id', $dist_user_id)
                                        ->orWhere('u.creator_id', $user_id);
                                });
                        });
                });
            }
            $distributions = Admin::where('status', 1)->where("user_type", 2)->where('creator_id', $user_id)->get();
        }

        if ($user_level == 1 || $user_level == 0) {
            $distributions = Admin::where('status', 1)->where("user_type", 2)->get();
        }

        $sorts = [
            'warranty_id' => 'w.warranty_id',
            'approved_date' => 'w.approved_date',
            'first_name' => 'w.first_name',
            'approved' => 'w.approved',
            'license_plate' => 'w.license_plate',
            'abbr' => 'u.abbr',
            'roll_number' => 'wvc.roll_number',
            // 'wvclen' => 'wvclen'
        ];
        $db = sortByColumn($db, $sorts);

        // $db = orderByCol($db, ['w.warranty_id', 'u.abbr', 'u.company_name', 'w.license_plate', 'w.installation_date', 'w.installer_name', 'wvc.roll_number']);
        // , 'wvc.roll_number'
        $db = filterByColumns($db, [
            'w.warranty_id',
            'w.phone_number',
            'w.first_name',
            'w.vin_number',
            'p.precut_id',
            'w.license_plate', 'w.dealer_name', 'w.installer_name', 'w.dealer_name', 'u.abbr', 'u.company_name' ,
            'wvc.roll_number'
        ]);

        // 特殊处理
        if(empty($_GET["startdate"]) && empty($_GET["enddate"])){
            $_GET["startdate"] =  date('Y-m-d 00:00:00', strtotime("-1 month"));
            $_GET["enddate"] = date('Y-m-d 23:59:59', time());
        }
        $db = filterByDateRange($db, 'w.approved_date');
        if (!empty($ids)) {
            $db = $db->whereIn('w.id', explode(',', $ids));
        }
        if ($request->input('status') !== null) {
            $db = $db->where('w.approved', $request->input('status'));
        }
        $db = $db->orderByDesc('w.id');
        if (!empty($request->input('product_type_id')) && in_array($request->input('product_type_id'), [1, 2])) {
            $db = $db->where('fm.product_type_id', $request->input('product_type_id'));
        }
        if (!empty($request->input('distribution_id'))) {
            $db = $db->where('w.distributor_id', $request->input('distribution_id'));
        }
        /*$data = $db->select(['w.*', 'u.company_name', 'u.abbr', DB::raw('sum(wvc.length) as wvclen')])
            ->paginate(50);*/
        // , DB::raw('sum(wvc.length) as wvclen')
        $data = $db->select([
            'w.id',
            'w.warranty_id',
            'w.license_plate',
            'w.first_name',
            'w.installer_name',
            'w.approved_date as installation_date',
            'w.user_id',
            'w.approved',
            'w.precut_id',
            'w.dealer_name',
            'u.company_name',
            'u.abbr',
            DB::raw('sum(wvc.length) as wvclen')
        ])
            ->paginate(50);
        // , 'wvc.roll_number'
        $wvc = [];
        if (!empty($data)) {
            $wvc = DB::table('warranty_to_vehicle_coverage')->whereNull('deleted_at')->whereIn('warranty_id', Arr::pluck($data, 'id'))->get();
        }
        $wvcs = [];
        foreach ($wvc as $w) {
            if (empty($wvcs[$w->warranty_id])) {
                $wvcs[$w->warranty_id] = [];
            }
            $wvcs[$w->warranty_id][] = $w;
        }
        foreach ($data as $k => $v) {
            $v->warranty_to_vehicle_coverage = @$wvcs[$v->id] ?: [];
            $v->status_zh = '审核';
        }
        if(gui()==1){
            # return $wvcs;
        }

        return view('admin.warranty.index', [
            'data'=> $data,
            'page' => $page,
            'user_level' => $user_level ?? 0,
            'menus' => $menus,
            'distributions' => $distributions ?? [],
            'user_type' => $user_level,
        ]);
    }

    public function indexV1(Request $request)
    {
        $page = [
            'page_name' => 'warranty',
            'title' => ts('MANAGEWARRANTY'),
        ];
        $user_id = session('admin.id');
        $user_level = session('admin.user_type');
        $db = DB::table('warranty', 'w')
            ->whereNull('w.deleted_at')
            ->leftJoin('users as u', 'w.user_id', '=', 'u.id')
            ->leftJoin('warranty_to_vehicle_coverage as wvc', 'w.id', '=', 'wvc.warranty_id')
            ->leftJoin('film_type_master as fm', 'fm.id', 'wc.film_type_id')
            ->groupBy('w.id');

        if ($user_level == 2) {
            $db = $db->where(function ($query) use ($user_id) {
                $query->orWhere('u.id', $user_id)
                    ->orWhere('u.creator_id', $user_id)
                    ->orWhere(function ($q2) use ($user_id) {
                        $q2->where('w.user_id', 0)
                            ->where('w.created_by', $user_id);
                    });
            });
        }
        $sorts = [
            'warranty_id' => 'w.warranty_id',
            'approved_date' => 'w.approved_date',
            'first_name' => 'w.first_name',
            'approved' => 'w.approved',
            'license_plate' => 'w.license_plate',
            'abbr' => 'u.abbr',
            'roll_number' => 'wvc.roll_number',
            // 'wvclen' => 'wvclen'
        ];
        $db = sortByColumn($db, $sorts);

        // $db = orderByCol($db, ['w.warranty_id', 'u.abbr', 'u.company_name', 'w.license_plate', 'w.installation_date', 'w.installer_name', 'wvc.roll_number']);
        // , 'wvc.roll_number'
        $db = filterByColumns($db, ['w.dealer_name', 'w.warranty_id', 'w.first_name', 'w.license_plate', 'w.installer_name', 'u.abbr', 'u.company_name' , 'wvc.roll_number']);

        $db = filterByDateRange($db, 'w.approved_date');
        /*$startdate = trim($request->input('startdate'));
        $enddate = trim($request->input('enddate'));
        if ($startdate) {
            $db = $db->where('installation_date', '>=', $startdate);
        }
        if ($enddate) {
            $db = $db->where('installation_date', '<=', $enddate);
        }*/
        if ($request->input('status') !== null) {
            $db = $db->where('approved', $request->input('status'));
        }
        if (!empty($request->input('product_type_id')) && in_array($request->input('product_type_id'), [1, 2])) {
            $db = $db->where('fm.product_type_id', $request->input('product_type_id'));
        }

        $db = $db->orderByDesc('id');

        /*$data = $db->select(['w.*', 'u.company_name', 'u.abbr', DB::raw('sum(wvc.length) as wvclen')])
            ->paginate(50);*/
        // , DB::raw('sum(wvc.length) as wvclen')
        $data = $db->select(['w.id', 'w.warranty_id', 'w.license_plate', 'w.first_name', 'w.installer_name', 'w.installation_date', 'w.approved', 'w.dealer_name', 'u.company_name', 'u.abbr', DB::raw('sum(wvc.length) as wvclen')])
            ->paginate(50);
        // , 'wvc.roll_number'
        $wvc = [];
        if (!empty($data)) {
            $wvc = DB::table('warranty_to_vehicle_coverage')->whereIn('warranty_id', Arr::pluck($data, 'id'))->get();
        }
        $wvcs = [];
        foreach ($wvc as $w) {
            if (empty($wvcs[$w->warranty_id])) {
                $wvcs[$w->warranty_id] = [];
            }
            $wvcs[$w->warranty_id][] = $w;
        }
        foreach ($data as $k => $v) {
            $v->warranty_to_vehicle_coverage = @$wvcs[$v->id] ?: [];
            $v->status_zh = '审核';
        }
        return view('admin.warranty.index', [
            'data'=> $data,
            'page' => $page,
        ]);
    }

    public function create(Request $request)
    {
        $user_type = session('admin.user_type');
        $unique_id = session('admin.unique_id');
        Refresh();
        /*if (session('admin.warranty_create') != 1) {
            return abort(404);
        }*/
        /*if ($user_type == 2) {
            if (!in_array($unique_id, ['CN00036', 'CN00037', 'CN00028'])) {
                return abort(404);
            }
        } else {
            checkAuthority();
        }*/
        $makes = MakeMaster::where('status', 1)->whereNull('deleted_at')->groupBy('simplified_chiness_value')->get();
        $page = [
            'page_name' => 'warranty',
            'title' => ts('ADDWARENTY'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        $data = new Warranty();
        $locale = App::getLocale();

        return view('admin.warranty.create', [
            'data'=>$data,
            'page' => $page,
            'makes' => $makes ?? [],
            'locale' => $locale,
        ]);
    }

    public function update(Request $request, $id)
    {
        $user_type = session('admin.user_type');
        $unique_id = session('admin.unique_id');
        $admin_id = session('admin.id');

        DB::beginTransaction();
        try {
            $model = Warranty::findOrFail($id);
            if ($model->approved == 1) {
                return redirect('/admin/warranty/')->with('trash', ['content'=>'已通过数据无法修改！', 'type'=>'error']);
            }
            if ($user_type != 1) {
                if ($model->approved !=3 && $model->approved != 2) {
                    return redirect()->back()->with('trash', ['content'=>'已提交审核数据无法修改！', 'type'=>'error']);
                }
                if (!empty($model->user_id)) {
                    if (!checkDealerBelongs($model->user_id)) {
                        return redirect()->back()->with('trash', ['content'=>'无权限操作该项数据！', 'type'=>'error']);
                    }
                } else {
                    if (!($model->created_by == $admin_id)) {
                        return redirect()->back()->with('trash', ['content'=>'无权限操作该项数据！', 'type'=>'error']);
                    }
                }
            }

            $alogs = alogs('质保', '修改', $model->id, null, $model);
            $diff = wDiff1($model);
            $model = wSave($model);
            if (empty($model->warranty_id)) {
                $model->warranty_id = makeWarrantyId($model->installation_date);
            }
            if (empty($model->created_by)) {
                $model->created_by = $admin_id;
            } else {
                $model->updated_by = $admin_id;
            }

            if ($make_name = $request->input('make_id')) {
                $make_id = getMakeId($make_name, $request->input('year_id'));
                if (empty($make_id)) {
                    $makeModel = new MakeMaster();
                    $makeModel->year_id = $request->input('year_id');
                    $makeModel->english_value = $make_name;
                    $makeModel->traditional_chiness_value = $make_name;
                    $makeModel->simplified_chiness_value = $make_name;
                    $makeModel->save();
                    $msg[] = "系统中不存在年份车辆品牌，已自动新增，请确认英文、繁体、简体内容是否正确：" . $request->input('year_id') . ' / ' . $make_name;
                    $make_id = $makeModel->id;

                    makeLangFiles();
                }
                $model->make_id = $make_id;
            }

            if ($model_name = $request->input('model_id')) {
                $model_id = getModelId($model_name, $make_id);
                if (empty($model_id)) {
                    $modelModel = new ModelMaster();
                    $modelModel->make_id = $make_id;
                    $modelModel->english_value = $model_name;
                    $modelModel->traditional_chiness_value = $model_name;
                    $modelModel->simplified_chiness_value = $model_name;
                    $modelModel->save();
                    $msg[] = "系统中不存在品牌车辆型号，已自动新增，请确认英文、繁体、简体内容是否正确：" . $request->input('year_id') . ' / ' . $model_name . ' / '.$make_name;
                    $model_id = $modelModel->id;
                    makeLangFiles();
                }
                $model->model_id = $model_id;
            }

            $model->approved = 3;
            $model->save();
            if (empty($model->pre_id)) {
                rwC($model); // 更新安装部位
            }
            rwI($model); // 更新安装图片
            $res = vWV4($model->id);

            if (!empty($res)) {
                DB::rollback();//数据库回滚
                $error_msg = @$res[0] ?: '服务器错误，请先保存草稿，稍后重试！';
                return redirect()->back()->withInput()->with('trash', ['content'=> $error_msg, 'type'=>'error']);
            } else {
                $dealer = Admin::withTrashed()->find($model->user_id);
                if (empty($dealer->id) || empty($dealer->abbr)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店为空或不存在！', 'type'=>'error']);
                }
                if ($dealer->user_type == 3) {
                    $distributor = Admin::withTrashed()->find($dealer->creator_id);
                    if (empty($distributor->id) || empty($distributor->abbr)) {
                        DB::rollback();
                        return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店所属不存在！', 'type'=>'error']);
                    }
                } else {
                    $distributor = $dealer;
                }
                $model->dealer_name = $dealer->abbr;
                $model->distributor_id = $distributor->id;
                $model->distributor_name = $distributor->abbr;

                $model->approved = 1;
                $model->approved_date = date('Y-m-d H:i:s');
                $model->save();
            }
            $coverages = WarrantyToVehicleCoverage::where('warranty_id', $model->id)
                ->get(['roll_number', 'length', 'part_id']);
            foreach ($coverages as $k => $v) {
                $roll = RollMaster::where('roll_number', $v->roll_number)->first();
                if (empty($roll)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '卷号不存在，请先保存草稿，稍后重试！', 'type'=>'error']);
                }
                /*if (in_array($v->part_id, [17, 18, 152, 150, 153])) {
                    $warrantyRollData = WarrantyToVehicleCoverage::where('warranty_id', '!=', $model->id)
                        ->where('roll_number', $v->roll_number)
                        ->whereIn('part_id', [17, 18, 152, 150, 153])
                        ->whereNull('deleted_at')
                        ->get();
                    if (!empty($warrantyRollData) && $warrantyRollData->isNotEmpty()) {
                        DB::rollback();
                        return redirect()->back()->withInput()->with('trash', ['content'=> $v->roll_number . '卷号已安装全车，稍后重试！', 'type'=>'error']);
                    }
                }*/

                $roll->status = 2;
                $roll->save();
                $e = minusRestlen($model->user_id, $v->roll_number, $v->length);
                if (empty($e)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '服务器错误，请先保存草稿，稍后重试！', 'type'=>'error']);
                }
            }

            if (!empty($diff)) {
                $wlogs = new WarrantyLogs();
                $wlogs->warranty_id = $model->id;
                $wlogs->status = 9;
                $wlogs->note = json_encode($diff);
                $wlogs->created_by = session('admin.id');
                $wlogs->save();
                $model->updated_by = $admin_id;
                $model->save();
            }
            $alogs->new = $model;
            $alogs->save();
            $this->insertWarrantyNotice($request, $model->id);

            $url = '/admin/warranty';
            session()->flash('hightlight', ['id'=>$model->id, 'type'=>'warranty']);
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请先保存草稿，稍后重试！', 'type'=>'error']);
        }
        sendSMS($model);
        $imgs = request()->input('images') ?? [];
        $this->syncToXp($model->warranty_id,implode(",",$imgs));
        return redirect($url)->with('trash', ts('WARRENTYADDSUCCESS'));
    }

    /*
     * 仅保存，并校验，校验通过后方允许提交*/
    public function store(Request $request)
    {
        Refresh();
        $user_type = session('admin.user_type');
        $unique_id = session('admin.unique_id');
        if (session('admin.warranty_create') != 1) {
            return abort(404);
        }/*
        if ($user_type == 2) {
            if (!cWPC()) {
                return abort(404);
            }
        } else {
            checkAuthority();
        }*/
        DB::beginTransaction();
        try {
            $admin_id = session('admin.id');
            $model = new Warranty();
            $diff = wDiff1($model);
            $model = wSave($model);

            if (empty($model->warranty_id)) {
                $model->warranty_id = makeWarrantyId($model->installation_date);
            }
            if (empty($model->created_by)) {
                $model->created_by = $admin_id;
            } else {
                $model->updated_by = $admin_id;
            }

            $year_id = $request->input('year_id');
            if ($make_name = $request->input('make_id')) {
                $make_id = getMakeId($make_name, $request->input('year_id'));
                if (empty($make_id)) {
                    $makeModel = new MakeMaster();
                    $makeModel->year_id = $request->input('year_id');
                    $makeModel->english_value = $make_name;
                    $makeModel->traditional_chiness_value = $make_name;
                    $makeModel->simplified_chiness_value = $make_name;
                    $makeModel->save();
                    $msg[] = "系统中不存在年份车辆品牌，已自动新增，请确认英文、繁体、简体内容是否正确：" . $year_id . ' / ' . $make_name;
                    $make_id = $makeModel->id;

                    makeLangFiles();
                }
                $model->make_id = $make_id;
            }

            if ($model_name = $request->input('model_id')) {
                $model_id = getModelId($model_name, $make_id);
                if (empty($model_id)) {
                    $modelModel = new ModelMaster();
                    $modelModel->make_id = $make_id;
                    $modelModel->english_value = $model_name;
                    $modelModel->traditional_chiness_value = $model_name;
                    $modelModel->simplified_chiness_value = $model_name;
                    $modelModel->save();
                    $msg[] = "系统中不存在品牌车辆型号，已自动新增，请确认英文、繁体、简体内容是否正确：" . $year_id . ' / ' . $model_name . ' / '.$make_name;
                    $model_id = $modelModel->id;
                    makeLangFiles();
                }
                $model->model_id = $model_id;
            }
            $model->approved = 3;
            $model->save();

            if (empty($model->pre_id)) {
                rwC($model); // 更新安装部位
            }
            rwI($model); // 更新安装图片

            $res = vWV4($model->id);
            if (!empty($res)) {
                DB::rollback();//数据库回滚
                $error_msg = @$res[0] ?: '服务器错误，请先保存草稿，稍后重试！';
                return redirect()->back()->withInput()->with('trash', ['content'=> $error_msg, 'type'=>'error']);
            } else {
                $dealer = Admin::withTrashed()->find($model->user_id);
                if (empty($dealer->id) || empty($dealer->abbr)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店为空或不存在！', 'type'=>'error']);
                }
                if ($dealer->user_type == 3) {
                    $distributor = Admin::withTrashed()->find($dealer->creator_id);
                    if (empty($distributor->id) || empty($distributor->abbr)) {
                        DB::rollback();
                        return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店所属不存在！', 'type'=>'error']);
                    }
                } else {
                    $distributor = $dealer;
                }
                $model->dealer_name = $dealer->abbr;
                $model->distributor_id = $distributor->id;
                $model->distributor_name = $distributor->abbr;
                $model->approved = 1;
                $model->approved_date = date('Y-m-d H:i:s');
                $model->save();
            }
            $coverages = WarrantyToVehicleCoverage::where('warranty_id', $model->id)
                ->get(['roll_number', 'length', 'part_id']);
            foreach ($coverages as $k => $v) {
                $roll = RollMaster::where('roll_number', $v->roll_number)->first();
                if (empty($roll)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '卷号不存在，请先保存草稿，稍后重试！', 'type'=>'error']);
                }
                /*if (in_array($v->part_id, [17, 18, 152, 150, 153])) {
                    $warrantyRollData = WarrantyToVehicleCoverage::where('warranty_id', '!=', $model->id)
                        ->where('roll_number', $v->roll_number)
                        ->whereIn('part_id', [17, 18, 152, 150, 153])
                        ->whereNull('deleted_at')
                        ->get();

                    if (!empty($warrantyRollData) && $warrantyRollData->isNotEmpty()) {
                        DB::rollback();
                        return redirect()->back()->withInput()->with('trash', ['content'=> $v->roll_number . '卷号已安装全车，稍后重试！', 'type'=>'error']);
                    }
                }*/
                $roll->status = 2;
                $roll->save();
                $e = minusRestlen($model->user_id, $v->roll_number, $v->length);
                if (empty($e)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '服务器错误，请先保存草稿，稍后重试！', 'type'=>'error']);
                }
            }

            if (!empty($diff)) {
                $wlogs = new WarrantyLogs();
                $wlogs->warranty_id = $model->id;
                $wlogs->status = 9;
                $wlogs->note = json_encode($diff);
                $wlogs->created_by = session('admin.id');
                $wlogs->save();
                $model->updated_by = $admin_id;
                $model->save();
            }

            $this->insertWarrantyNotice($request, $model->id);
            $alogs = alogs('质保', '添加', $model->id, $model, null);
            $url = '/admin/warranty';
            session()->flash('hightlight', ['id'=>$model->id, 'type'=>'warranty']);
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请先保存草稿，稍后重试！', 'type'=>'error']);
        }

        sendSMS($model);
        $imgs = request()->input('images');
        $this->syncToXp($model->warranty_id,implode(",",$imgs));

        return redirect($url)->with('trash', ts('WARRENTYADDSUCCESS'));
    }

    public function syncToXp($warrantyId,$images){
        try{
            $httpCore = new RequestCore("https://xcx.xpel.com.cn/api/order/syncWarranty?warranty_id=$warrantyId&images=$images");
            $httpCore->set_method("GET");
            $httpCore->connect_timeout = 60;
            $httpCore->timeout = 60;
            $res = $httpCore->send_request();
        }catch (\Exception $e){
        }
    }
    /**
     * 插入质保通知
     *
     * @param Request $request
     * @param $warrantyId
     * @return bool
     */
    public function insertWarrantyNotice(Request $request, $warrantyId)
    {
        $user = Admin::where('id', $request->input('user_id'))->first();
        if (empty($user) || empty($user->city)) {
            return false;
        }
        $warranty = DB::table('warranty_notice')->where('warranty_id', $warrantyId)->whereNull('deleted_at')->first();
        if (!empty($warranty)) {
            if ($request->input('city') == $user->city) {
                $result = (new UserService())->getMobileArea($request->input('phone_number'));
                if (empty($result) || empty($result['city'])) {
                    return false;
                }
                $city = Cities::where('id', $user->city);
                if (empty($city)) {
                    return false;
                }
                if (mb_strpos($result['city'], $city->simplified_chiness_value) !== false) {
                    DB::table('warranty_notice')->where('warranty_id', $warrantyId)->update(['deleted_at' => date('Y-m-d H:i:s')]);
                }
                return true;
            }
            $result = (new UserService())->getMobileArea($request->input('phone_number'));
            if (empty($result) || empty($result['city'])) {
                return false;
            }
            $city = Cities::where('id', $user->city);
            if (empty($city)) {
                return false;
            }
            if (mb_strpos($result['city'], $city->simplified_chiness_value) === false) {
                DB::table('warranty_notice')->insert([
                    'warranty_id'   => $warrantyId,
                    'user_id'       => $request->input('user_id')
                ]);
            }
            return false;
        }


        if ($request->input('city') != $user->city) {
            DB::table('warranty_notice')->insert([
                'warranty_id'   => $warrantyId,
                'user_id'       => $request->input('user_id')
            ]);
            return true;
        }
        $result = (new UserService())->getMobileArea($request->input('phone_number'));
        if (empty($result) || empty($result['city'])) {
            return false;
        }
        $city = Cities::where('id', $user->city)->first();
        if (empty($city)) {
            return false;
        }
        if (mb_strpos($city->simplified_chiness_value, $result['city']) === false) {
            DB::table('warranty_notice')->insert([
                'warranty_id'   => $warrantyId,
                'user_id'       => $request->input('user_id')
            ]);
        }
    }

    public function handle_import(Request $request)
    {

        Log::channel('wlog')->info(json_encode(['质保导入开始']));
        $admin_id = session('admin.id');
        $file = $request->file('file');
        if (empty($file)) {
            return redirect()->back()->withInput()->with('trash', ['content'=>'文件不存在！', 'type'=>'error']);
        }
        if ($file->getClientOriginalExtension() != 'xlsx') {
            return redirect()->back()->withInput()->with('trash', ['content'=>'仅支持上传xlsx类型文件', 'type'=>'error']);
        }
        $filename = time().Str::random(4) . '.xlsx';
        $path = getFileStorePath(2);
        $bool = $file->storeAs($path['path'], $filename, 'storage');
        $full_file_name = $path['path'].$filename; // /upload/XXX/filename
        $mod = new FileUpload();
        $mod->type = 2;
        $mod->name = '质保文件上传';
        $mod->user_id = $admin_id;
        $mod->file = $full_file_name;
        $mod->save();


        DB::beginTransaction();
        try {
            $data = $this->parseWarrantyExcelFile($path['base'] . $filename);
            if (empty(@$data->id)) {
                DB::rollback();
                return redirect()->back()->withInput()->with('trash', ['content'=>'导入失败，请确认文件内容！', 'type'=>'error']);
            } else {
                DB::commit();
            }
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            $info = [
                'chanel' => '质保Excel导入',
                'exception' => $exception,
            ];
            Log::channel('wlog')->info(json_encode($info));
            return redirect()->back()->withInput()->with('trash', ['content'=>'导入失败，请刷新页面重试！'.$exception, 'type'=>'error']);
        }

        session()->flash('warranty_import_result', 1);
        session()->flash('hightlight', ['id'=>$data->id, 'type'=>'warranty']);
        return redirect('/admin/warranty/'.$data->id.'/edit')->with('trash', '导入成功！');
    }

    /*
     * 根据Excel内容展示warning*/
    public function parseWarrantyExcelFile($file)
    {
        $admin_id = session('admin.id');
        if (!file_exists($file) || !is_file($file)) {
            return abort(404);
        }
        $spreadsheet = IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();

        $first_name = $sheet->getCell('A4')->getValue();
        $region = $sheet->getCell('B4')->getValue(); // 获取id
        $province = $sheet->getCell('C4')->getValue(); // 获取id
        $city = $sheet->getCell('D4')->getValue(); // 获取id
        $zip = $sheet->getCell('E4')->getValue();
        $email_address = $sheet->getCell('F4')->getValue();
        $phone_number_2 = $sheet->getCell('G4')->getValue(); // 获取电话与extension 原文，-分割
        $address = $sheet->getCell('B5')->getValue();
        $year_id = $sheet->getCell('A8')->getValue();
        $make_name = $sheet->getCell('B8')->getValue(); // 获取make_id
        $model_name = $sheet->getCell('C8')->getValue(); // 获取model_id
        $license_plate = $sheet->getCell('E8')->getValue(); // 车牌
        $license_plate = strtoupper($license_plate);
        $vin_number = $sheet->getCell('F8')->getValue(); // 车架号
        $vin_number = strtoupper($vin_number);

        $qudao = $sheet->getCell('A11')->getValue(); // 装贴门店
        $installer_name = $sheet->getCell('B11')->getValue(); // 装贴技师
        $C11 = $sheet->getCell('C11')->getValue(); // 安装日期
        try {
            if (is_string($C11)) {
                $C11 = trim($C11);
                if (mb_strpos($C11, '年')) {
                    $idate_arr = date_parse_from_format('Y年m月d日',$C11);
                    $installation_date = mktime(0,0,0,$idate_arr['month'],$idate_arr['day'],$idate_arr['year']);
                    // $installation_date = date('Y-m-d', $installation_date);
                } else {
                    $installation_date = strtotime($C11);
                    // $installation_date = date('Y-m-d', $installation_date);
                }
            } else {
                $installation_date = Date::excelToTimestamp($C11);
            }
        } catch (\Exception $exception) {
            $installation_date = 0;
        }
        if (strtotime($installation_date) > strtotime(date('Y-m-d'))) {
            $msg[] = "安装日期超过今天";
        }
        $installation_price = $sheet->getCell('E11')->getValue(); // 安装价格
        Log::channel('wlog')->info(json_encode(['质保导入解析图片开始']));
        $installation_images_zip_url = $spreadsheet->getActiveSheet()->getCell('G11')->getHyperlink()->getUrl(); // 安装图片地址
        $installation_images = $this->getInstalationImagesByZipUrl($installation_images_zip_url);
        Log::channel('wlog')->info(json_encode(['质保导入解析图片结束']));

        $msg = [];

        if (empty($first_name)) {
            $msg[] = "车主姓名 不能为空！" . $first_name;
        }
        if (empty($email_address)) {
            $msg[] = "电子邮件 不能为空！" . $email_address;
        } else {
            if (empty(cEmail($email_address))) {
                $msg[] = "电子邮件 格式不符合规范：" . $email_address;
            }
        }

        if (empty($license_plate)) {
            # $msg[] = "牌照号 不能为空：" . $license_plate;
        }

        if (empty($vin_number)) {
            $msg[] = "车架号 不能为空：" . $vin_number;
        } else {
            if (!pregV1('vin_number', $vin_number)) {
                $msg[] = "车架号 格式不符合规范：" . $vin_number;
            }
        }
        if (empty($address)) {
            $msg[] = "车主地址 不能为空：" . $address;
        }

        $qudao_user = getUserByName($qudao);
        $qudao_id = @$qudao_user->id ?: 0;
        if (empty($qudao_user->id)) {
            $msg[] = "装贴门店 不存在：" . $qudao;
        } else if ($qudao_user->trashed()) {
            $msg[] = "装贴门店 已被禁用：" . $qudao;
        } elseif ($qudao_user->status != 1) {
            $msg[] = "装贴门店 已被停用：" . $qudao;
        } elseif ($qudao_user->user_type == 3 && $qudao_user->check_status == 2) {
            $msg[] = "装贴门店 审核已被拒绝：" . $qudao;
        }
        if (!empty($qudao_id)) {
            if (@$qudao_user->id == $admin_id || @$qudao_user->creator_id == $admin_id) {

            } else {
                if (!checkDealerBelongs($qudao_id)) {
                    $qudao_id = 0;
                    $msg[] = '装贴门店非下属门店，请确认：'.$qudao_user->abbr;
                }
            }
        }

        $region_id = 0;
        $province_id = 0;
        $city_id = 0;
        if (empty($region)) {
            $msg[] = "地区为空，省、城市需要重新设置，请确认：". $region . ' / ' .  $province. ' / ' . $city;
        } else {
            $region_id = getColumnIdByName2('region_master', $region);
            if (empty($region_id)) {
                $msg[] = "地区不存在，省、城市需要重新设置，请确认：". $region . ' / ' .  $province. ' / ' . $city;
            }
        }
        if (!empty($region_id)) {
            if (empty($province)) {
                $msg[] = "省为空，城市需要重新设置，请确认：" .  $region . ' / ' .  $province. ' / ' . $city;
            } else {
                $province_id = getColumnIdByName2('province_master', $province, $region_id);
                if (empty($province_id)) {
                    $msg[] = "地区下省不存在，城市需要重新设置，请确认：" . $region . ' / ' .  $province. ' / ' . $city;
                }
            }
        }
        if (!empty($province_id)) {
            if (empty($city)) {
                $msg[] = "城市为空：" . $region . ' / ' .  $province;
            } else {
                $city_id = getColumnIdByName2('cities', $city, $province_id);
                if (empty($city_id)) {
                    $msg[] = "省内城市不存在，请确认：" . $province. ' / ' . $city;
                }
            }
        }

        $pns = explode('-', $phone_number_2, 2);
        if (count($pns) != 2) {
            $msg[] = "电话号码有误，区号或电话号码不完整，系统默认增加地区号【+86】，请确认：" . $phone_number_2;
            $extension = '+86';
            $phone_number = trim($pns[0]);
        } else {
            $extension = trim($pns[0]);
            if (in_array($extension, ['+86', '+886', '+852', '+853'])) {
                $extension = $extension;
            } else if (in_array($extension, ['86', '886', '852', '853'])) {
                $extension = '+'.$extension;
            } else {
                $extension = '+86';
            }
            $phone_number = trim($pns[1]);
        }

        if ($extension == '+86') {
            if ($license_plate && !pregV1('license_plate', $license_plate)) {
                $msg[] = "牌照号 格式不符合规范：" . $license_plate;
            }
            if ($phone_number && !pregV1('phone_number', $phone_number)) {
                $msg[] = "联系电话 格式不符合规范：" . $phone_number;
            }
        }

        if (empty($installer_name)) {
            $msg[] = "装贴技师 不能为空：" . $installer_name;
        }
        if (empty($installation_date)) {
            $msg[] = "装贴日期 不能为空：" . $C11;
        }
        if ($installation_date > time()) {
            $msg[] = "装贴日期 不能选择未来的日期：" . date('Y-m-d', $installation_date);
        }
        if (empty($installation_price)) {
            $msg[] = "装贴价格 不能为空：" . $installation_price;
        }
        $make_id = $model_id = 0;
        $year_id = (int) $year_id;
        if (empty($year_id)) {
            $msg[] = "车辆年份为空，车辆品牌、车辆型号需要重新设置，并联系管理员新增：" . $make_name. ' / ' . $model_name;
        } else {
            if (empty($make_name)) {
                $msg[] = "车辆品牌为空，车辆型号需要重新设置，并联系管理员新增：" . $year_id. ' / ' . $make_name. ' / ' . $model_name;
            } else {
                $make_id = getMakeId($make_name, $year_id);
                if (empty($make_id)) {
                    /*$makeModel = new MakeMaster();
                    $makeModel->year_id = $year_id;
                    $makeModel->english_value = $make_name;
                    $makeModel->traditional_chiness_value = $make_name;
                    $makeModel->simplified_chiness_value = $make_name;
                    $makeModel->status = 1;
                    $makeModel->save();
                    $make_id = $makeModel->id;
                    makeLangFiles();*/
                    $msg[] = "系统中无此车型，请联系管理员进行新增：" . $year_id . ' / ' . $make_name;
                }
            }
        }
        if (!empty($make_id)) {
            if (empty($make_name)) {
                $msg[] = "车辆型号为空：" . $year_id . ' / ' . $make_name;
            } else {
                $model_id = getModelId($model_name, $make_id);
                if (empty($model_id)) {
                    /*$modelModel = new ModelMaster();
                    $modelModel->make_id = $make_id;
                    $modelModel->english_value = $model_name;
                    $modelModel->traditional_chiness_value = $model_name;
                    $modelModel->simplified_chiness_value = $model_name;
                    $modelModel->status = 1;
                    $modelModel->save();
                    $model_id = $modelModel->id;
                    makeLangFiles();*/
                    $msg[] = "系统中无此车型，请联系管理员进行新增：" . $year_id . ' / ' . $model_name . ' / '.$make_name;
                }
            }
        }
        /*
         * 安装部位*/
        $vehicles = [];
        $row_no = 14;
        $max_row = 30;
        $n = '';
        while ($row_no<=$max_row && $n != '补充说明'){
            $item = [];
            $part = $sheet->getCell('A'.$row_no)->getValue(); // 套件
            $precut_or_manual = $sheet->getCell('B'.$row_no)->getValue(); // 裁切或手工
            $roll_number = $sheet->getCell('C'.$row_no)->getValue(); // 卷号
            $length = $sheet->getCell('E'.$row_no)->getValue(); // 使用长度
            $film_type_name = $sheet->getCell('F'.$row_no)->getValue(); // 膜的种类
            $width = $sheet->getCell('G'.$row_no)->getValue(); // 薄膜宽度
            $part = trim($part);
            if (empty($part) || $part == '补充说明') {
                $n = '补充说明';
            } else {
                $len_txt = str_replace(' ', '', $length);
                $len_txt = str_replace('    ', '', $len_txt);
                if (mb_strpos ($len_txt, '厘米') !== false) {
                    $mlen = str_replace('厘米', '', $len_txt);
                    $mlen = trim($mlen);
                    $length_ = (int) $mlen;
                } elseif (mb_strpos ($len_txt, '米') !== false) {
                    $mlen = str_replace('米', '', $len_txt);
                    $mlen = trim($mlen);
                    $length_ = (int) (100 * $mlen);
                } else {
                    $length_ = (int) $len_txt;
                }
                $width_ = (int) $width;
                $part_id = 0;
                if (empty($part)) {
                    $msg[] = "装贴部位 不能为空！";
                } else {
                    $part_id = getColumnIdByName2('part_master', $part);
                    $part_model = getColumnByName3('part_master', $part);
                    if (empty($part_id)) {
                        $msg[] = "装贴部位不存在，请联系管理员新增：" . $part; // 第 {$row_no} 行
                    }
                }

                $rne = getRollsMasterByRollNumber($roll_number);
                if (empty($rne->id)) {
                    $msg[] = "膜卷号不存在，请联系管理员新增：" . $roll_number;
                } else {
                    $film_model = FilmTypeMaster::find(@$rne->film_type_id);
                    /*if (!empty(@$rne->id) && !empty($part_id)) {
                        if (@$film_model->product_type_id != @$part_model->product_type_id) {
                            $msg[] = "膜卷号与装贴部位产品类型不一致，请确认：" . $roll_number . ' / ' . $part;
                        }
                    }*/
                }
                if (!empty($rne->deleted_at)) {
                    $msg[] = "膜卷号已被删除，无法继续使用：" . $roll_number;
                }
                if (empty($length_)) {
                    $msg[] = "用料长度（CM）为0或非数字：" . $length;
                }

                $fld = getColumnIdByName2('film_type_master', $film_type_name);
                $film_type_id = @$rne->film_type_id;
                if (@$rne->id && $film_type_id != $fld) {
                    $msg[] = "膜型号与系统中不一致，请再次确认：" . $film_type_name . ' / ' . ts('film_type_master.'.$film_type_id);
                }
                $item = [
                    'precut_or_manual' => $precut_or_manual == '手工' ? 2 : 1,
                    'part_id' => $part_id,
                    'roll_number' => $roll_number,
                    'length' => $length_,
                    'width' => $width_,
                    'film_type_id' => $film_type_id,
                ];
                $vehicles[] = $item;
            }
            $row_no++;
        }
        $additional_comments = $sheet->getCell('A'.$row_no)->getValue();

        $user_id = session('admin.id');
        $model = new Warranty();
        $model->user_id = $qudao_id;
        $model->first_name = trim($first_name);
        $model->address = trim($address);
        $model->city = $city_id;
        $model->province_id = $province_id;
        $model->zip = trim($zip);
        $model->region_id = $region_id;
        $model->email_address = trim($email_address);
        $model->phone_number = $phone_number;
        $model->extension = $extension;
        $model->installer_name = trim($installer_name);
        $model->installation_date = date('Y-m-d H:i:s', $installation_date);
        $model->installation_price = trim($installation_price);
        $model->year_id = trim($year_id);
        $model->make_id = $make_id;
        $model->model_id = $model_id;
        $model->license_plate = trim($license_plate);
        $model->vin_number = trim($vin_number);
        $model->additional_comments = trim($additional_comments);

        $model->created_by = $admin_id;
        $model->warranty_id = makeWarrantyId($model->installation_date);
        $model->approved = 3;
        $model->save();

        $dtime = gDate();
        // 更新安装部位
        DB::table('warranty_to_vehicle_coverage')->where('warranty_id', $model->id)->delete();
        $uploads = [];
        foreach ($vehicles as $vk => $vv) {
            $vv['warranty_id'] = $model->id;
            $vv['created_at'] = $dtime;
            $vv['updated_at'] = $dtime;
            $uploads[] = $vv;
        }
        DB::table('warranty_to_vehicle_coverage')->insert($uploads);

        $rols = Arr::pluck($uploads, 'roll_number');
        if (!empty($qudao_id)) {
            $rls = [];
            foreach ($uploads as $k => $v) {
                $rls[$v['roll_number']] = @$rls[$v['roll_number']] + $v['length'];
            }
            $rolens = getRlens401($rols, $qudao_id);
            foreach ($rls as $k => $v) {
                $rne = getRollsMasterByRollNumber($k);
                if (empty($rne->id) || !empty($rne->deleted_at)) {
                    continue;
                }
                if ($v > @$rolens[$k]) {
                    $msg[] = "装贴门店膜卷号可使用长度不足，请联系管理员分配：" . $k;
                }
            }
        } else {
            $rls = [];
            foreach ($uploads as $k => $v) {
                $rls[$v['roll_number']] = @$rls[$v['roll_number']] + $v['length'];
            }
            foreach ($rls as $k => $v) {
                $msg[] = $k . " 该卷号不属于该门店；";
            }

        }

        $imgs = [];
        $rmg = $installation_images;
        foreach ($rmg as $k => $v) {
            $item = [];
            $item['warranty_id'] = $model->id;
            $item['created_at'] = $dtime;
            $item['updated_at'] = $dtime;
            $item['image_src'] = $v;
            $item['part_id'] = $k+1;
            $imgs[] = $item;
        }
        if (empty($imgs)) {
            $msg[] = "安装图片为空，请确认；";
        } else {
            DB::table('warranty_image')->insert($imgs);
            if (count($imgs) < 6 || count($imgs) > 12) {
                $msg[] = "安装图片保证清晰且最多12张，最少6张；";
            }
        }

        $alogs = alogs('质保', '导入', $model->id, $model, null);
        $msgModel = new WarrantyMsg();
        $msgModel->content = json_encode($msg);
        $msgModel->warranty_id = $model->id;
        $msgModel->status = 0;
        $msgModel->save();


        Log::channel('wlog')->info(json_encode(['其他数据判断及存储']));
        return $model;
    }
    /*
     * 根据链接获取压缩包
     * 解压
     * 获取压缩包内的图片
     * 上传到七牛云，并返回链接地址
     * 返回地址数组*/
    protected function getInstalationImagesByZipUrl($url)
    {
        $filename = Str::random(16) . '.zip';
        $path = getFileStorePath(2);
        $full_file_name = $path['base'] . $filename;
        $bool = file_put_contents($full_file_name, file_get_contents($url));
        $filenames = [];
        $info = mime_content_type($full_file_name);
        if ($info == 'application/zip') {
            $zip = zip_open($full_file_name);
            while ($zip_entry = zip_read($zip)) {
                if (zip_entry_open($zip, $zip_entry, "r")) {
                    $file_name = zip_entry_name($zip_entry);
                    $pfn = pathinfo($file_name);
                    if (!empty($pfn['extension']) && in_array($pfn['extension'], ['jpg', 'jpeg', 'png', 'gif'])) {
                        $content = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));
                        $ym = date('Ym');
                        $path = public_path('upload/'.$ym);
                        if (!file_exists($path)) {
                            mkdir($path, 0755, true);
                        }
                        $fileName = Str::random(30).'.jpg';

                        $imageUrl = (new UploadService())->uploadAliOss($content, $ym . '/' . $fileName);
                        if (empty($imageUrl['oss-request-url'])) {
                            continue;
                        }
                        $filenames[] = str_replace('https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com', 'https://image-xpel.dengwho.com', $imageUrl['oss-request-url']);

                        //file_put_contents($path.'/'.$fileName, $content);
                        //$filenames[] = '/upload/'.$ym.'/'.$fileName;
                        /*$pf = pathinfo($file_name);
                        $k = $pf['filename'];
                        $fileName = Str::random(32).'.jpg';
                        $temp = tmpfile();
                        fwrite($temp, $content);
                        $temppath = stream_get_meta_data($temp)['uri'];
                        $ret = uploadFile($temppath, $fileName);
                        if (@$ret['status'] == 'SUCCESS') {
                            $filenames[$k] = $ret['data']['url'];
                        } else {
                            $path = public_path('upload/images');
                            $fileName = Str::random(30).'.jpg';
                            file_put_contents($path.'/'.$fileName, $content);
                            $filenames[$k] = '/upload/images/'.$fileName;
                        }
                        fclose($temp);
                        */
                    }
                }
                zip_entry_close($zip_entry);
            }
        }
        return $filenames;
    }


    /*
     * 质保修改*/
    public function edit(Request $request, $id)
    {
        $model = Warranty::findOrFail($id);
        $ut = session('admin.user_type');
        $uid = session('admin.id');
        if (empty($model->warranty_id)) {
            $model->warranty_id = makeWarrantyId($model->installation_date);
            $model->save();
        }
        if ($model->approved == 1) {
            return redirect('/admin/warranty/')->with('trash', ['content'=>'已通过数据无法修改！', 'type'=>'error']);
        }
        if (session('warranty_import_result')!=1) {
            vWV4($id);
        }
        if ($model->approved == 2) {
            if (!empty($model->pre_id)) {
                $wvcs = DB::table('warranty_to_vehicle_coverage')->where('warranty_id', $model->id)->get();
                foreach ($wvcs as $k => $v) {
                    plusRestlen($model->user_id, $v['roll_number'], $v['length']); // 重新提交重新计算
                }
            }
            $model->approved = 3;
            $model->save();
        }
        if ($ut != 1) {
            if ($model->approved !=3 && $model->approved != 2) {
                return redirect('/admin/warranty/')->with('trash', ['content'=>'已提交审核数据无法修改！', 'type'=>'error']);
            }

            if (!empty($model->user_id)) {
                if (!checkDealerBelongs($model->user_id)) {
                    return redirect('/admin/warranty/')->with('trash', ['content'=>'未知数据！', 'type'=>'error']);
                }
            } else {
                if (!($model->created_by == $uid)) {
                    return redirect('/admin/warranty/')->with('trash', ['content'=>'未知数据！', 'type'=>'error']);
                }
            }
        }
        $page = [
            'page_name' => 'warranty',
            'title' => ts('EDITWARENTY'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        $makes = MakeMaster::whereNull('deleted_at')->groupBy('simplified_chiness_value')->get();
        $make_name = MakeMaster::where('id', $model->make_id)->first();
        $model_name = ModelMaster::where('id', $model->model_id)->first();
        if (!empty($make_name)) {
            $models = ModelMaster::whereNull('deleted_at')
                ->whereIn('make_id', function ($query) use ($make_name) {
                    $query->select('id')
                        ->from('make_master')
                        ->where('simplified_chiness_value', $make_name->simplified_chiness_value);
                })
                ->whereNull('deleted_at')
                ->groupBy('simplified_chiness_value')
                ->get();
        }
        return view('admin.warranty.edit', [
            'data'          =>$model,
            'page'          => $page,
            'makes'         => $makes ?? [],
            'models'        => $models ?? [],
            'make_name'     => $make_name ? $make_name->simplified_chiness_value : '',
            'model_name'    => $model_name ? $model_name->simplified_chiness_value : '',
        ]);
    }


    public function install(Request $request)
    {
        $page = [
            'page_name' => 'precut',
            'title' => ts('installer'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEPRECUT'),
                    'url' => '/admin/new-precut'
                ]
            ],
        ];
        $data = new Warranty();
        $coverages = [];
        return view('admin.warranty.new-install', [
            'page' => $page,
            'data' => $data, // $model
            'coverages' => $coverages,
        ]);
    }
    /*
     * 管理员无法使用套餐安装*/
    public function handle_install(Request $request)
    {
        $admin_id = session('admin.id');
        $user_type = session('admin.user_type');
        if ($user_type == 1) {
            $admin_id = 1;
            abort(404);
        }
        $id = $request->input('precut_id');
        DB::beginTransaction();
        try {
            // $precut = Precut::lockForUpdate()->find($id);
            $precut = NewPrecut::lockForUpdate()->find($id);
            if ($precut->status == 1) {
                return redirect('/admin/new-precut')->with('trash', ['content'=>'专车专用套件不允许重复安装！', 'type'=>'error']);
            }
            if (empty($precut->id)) {
                return redirect('/admin/new-precut')->with('trash', ['content'=>'专车专用套件没有找到，请确认！', 'type'=>'error']);
            }
            if (empty($precut->user_id)) {
                return redirect('/admin/new-precut')->with('trash', ['content'=>'套件尚未分配，请联系管理员分配！', 'type'=>'error']);
            }
            if (!checkDealerBelongs($precut->user_id)) {
                return redirect('/admin/new-precut')->with('trash', ['content'=>'套件未分配给当前用户，请联系管理员分配！', 'type'=>'error']);
            }
            $warranty = Warranty::firstOrNew(['precut_id' => $precut->id]);
            if (!empty($warranty->id)) {
                return redirect('/admin/new-precut')->with('trash', ['content'=>'质保系统中已有套件安装记录，请确认！', 'type'=>'error']);
            }
            $warranty = wSave($warranty);
            if (empty($warranty->warranty_id)) {
                $warranty->warranty_id = makeWarrantyId($warranty->installation_date);
            }
            $warranty->precut_id = $precut->id;
            $warranty->created_by = $admin_id;
            $warranty->approved = 3;
            $warranty->save();
            // rwI($warranty);
            $res = vWV4($warranty->id);
            if (!empty($res)) {
                DB::rollback();//数据库回滚
                $error_msg = @$res[0] ?: '服务器错误，请先保存草稿，稍后重试！';
                return redirect()->back()->withInput()->with('trash', ['content'=> $error_msg, 'type'=>'error']);
            } else {
                $dealer = Admin::withTrashed()->find($warranty->user_id);
                if (empty($dealer->id) || empty($dealer->abbr)) {
                    DB::rollback();
                    return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店为空或不存在！', 'type'=>'error']);
                }
                if ($dealer->user_type == 3) {
                    $distributor = Admin::withTrashed()->find($dealer->creator_id);
                    if (empty($distributor->id) || empty($distributor->abbr)) {
                        DB::rollback();
                        return redirect()->back()->withInput()->with('trash', ['content'=> '装贴门店所属不存在！', 'type'=>'error']);
                    }
                } else {
                    $distributor = $dealer;
                }
                $warranty->dealer_name = $dealer->abbr;
                $warranty->distributor_id = $distributor->id;
                $warranty->distributor_name = $distributor->abbr;
                $warranty->approved = 1;
                $warranty->approved_date = date('Y-m-d H:i:s');
                $warranty->save();
            }

            $precut->status = 1;
            $precut->save();

            $alogs = alogs('质保', '安装', $warranty->id, $warranty, null);
            $url = '/admin/warranty';
            session()->flash('hightlight', ['id'=>$warranty->id, 'type'=>'warranty']);
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请先保存草稿，稍后重试！', 'type'=>'error']);
        }

        return redirect($url)->with('trash', ts('warrantyADDSUCCESS'));
    }

    /*仅管理员可以删除、编辑修改*/
    /*
     * 非管理员可以删除待提交或者被拒绝数据
     * 产品表仅需要根据质保ID查询
     * 主判断满足条件下的质保是否存在，假如存在则删除，否则不删除*/
    public function delete(Request $request, $id)
    {
        return deleteWarranty($id);
    }
    public function deletes(Request $request)
    {
        $ids = $request->input('id');
        if (empty($ids)) {
            return ['status'=>false, 'msg'=>'参数错误！'];
        }
        foreach ($ids as $k => $id) {
            deleteWarranty($id);
        }
        return ['status' => 'SUCCESS', 'msg' => '质保信息删除成功！'];
    }

    public function import()
    {
        $page = [
            'page_name' => 'warranty',
            'title' => ts('bulkimport'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        return view('admin.warranty.import', [
            'page' => $page,
        ]);
    }

    public function show(Request $request, $id)
    {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        $page = [
            'page_name' => 'warranty',
            'title' => ts('VIEWWARENTY'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        $data = Warranty::findOrFail($id);
        $dealer = Admin::withTrashed()->find($data->user_id);
        rwI($data);
        if ($user_type!=1 && $user_type != 4) {
            if ($data->approved == 1) {
                if(empty($data->distributor_id)) {
                    if ($data->user_id != $user_id && @$dealer->creator_id != $user_id) {
                        return abort(404);
                    }
                } else {
                    if ($data->distributor_id != $user_id) {
                        return abort(404);
                    }
                }
            } else {
                if (empty($data->user_id)) {
                    if ($data->created_by != $user_id) {
                        return abort(404);
                    }
                } else {
                    if ($data->user_id != $user_id && @$dealer->creator_id != $user_id) {
                        return abort(404);
                    }
                }
            }
        }

        $images = Warranty::where('warranty_id', $data->id)->get();
        $coveragse = WarrantyToVehicleCoverage::where('warranty_id', $data->id)->get();
        foreach ($coveragse as $k => $v) {
            $cmodel = WarrantyToVehicleCoverage::find($v->id);
            $rmodel = getRollsMasterByRollNumber($v->roll_number);
            if (!empty($rmodel->film_type_id)) {
                if ($cmodel->film_type_id != $rmodel->film_type_id || $cmodel->width != $rmodel->width) {
                    $cmodel->film_type_id = $rmodel->film_type_id;
                    $cmodel->width = $rmodel->width;
                    $cmodel->save();
                }
            }
        }

        if (session('admin.user_type') == 2) {
            $deleteRecord = DB::table('warranty_delete')->where('warranty_id', $data->warranty_id)->first();
        }

        return view('admin.warranty.show', [
            'data'=>$data,
            'page' => $page,
            'user_type' => session('admin.user_type'),
            'delete_record' => $deleteRecord ?? '',
        ]);
    }

    public function export(Request $request)
    {
        set_time_limit(0);
        $user_id = session('admin.id');
        $user_level = session('admin.user_type');
        $db = DB::table('warranty', 'w')
            ->whereNull('w.deleted_at')
            ->leftJoin('users as u', 'w.user_id', '=', 'u.id')
            ->leftJoin('warranty_to_vehicle_coverage as wvc', 'w.id', '=', 'wvc.warranty_id')
            ->leftJoin('film_type_master as fm', 'fm.id', '=', 'wvc.film_type_id')
            ->leftJoin('region_master as rm', 'rm.id', 'w.region_id')
            ->leftJoin('province_master as pm', 'pm.id', 'w.province_id')
            ->leftJoin('cities as ct', 'ct.id', 'w.city')

            ->leftJoin('make_master as mm', 'mm.id', 'w.make_id')


            ->whereNull('wvc.deleted_at')
            ->where('w.approved', 1)

            ->groupBy('w.id');

        if ($user_level == 2) {
            $db = $db->where(function ($query) use ($user_id) {
                $query->where([
                    'w.distributor_id' => $user_id,
                    'w.approved' => 1
                ])
                    ->orWhere(function ($q2) use ($user_id) {
                        $q2->where('w.approved', '!=', 1)
                            ->where(function ($q3) use ($user_id) {
                                $q3->where([
                                    'w.user_id' => 0,
                                    'w.created_by' => $user_id
                                ])
                                    ->orWhere('u.id', $user_id)
                                    ->orWhere('u.creator_id', $user_id);
                            });
                    });
            });
        }
        if (!empty($request->input('ids'))) {
            $db = $db->whereIn('w.id', explode(',', $request->input('ids')));
        }
        if (!empty($request->input('status'))) {
            $db = $db->where('w.approved', $request->input('status'));
        }
        if (!empty($request->input('distribution_id'))) {
            $dealer_ids = (new UserService())->getDealers([$request->input('distribution_id')]);
            $dealer_ids[] = $request->input('distribution_id');
            $db = $db->whereIn('w.user_id', $dealer_ids);
        }

        if (!empty($request->input('product_type_id'))) {
            $db = $db->where('fm.product_type_id', $request->input('product_type_id'));
        }

        $db = filterByColumns($db, [
            'w.warranty_id',
            'w.phone_number',
            'w.first_name',
            'w.license_plate',
            'w.dealer_name',
            'w.installer_name',
            'w.dealer_name',
            'u.abbr',
            'u.company_name',
            'wvc.roll_number'
        ]);

        $db = filterByDateRange($db, 'w.approved_date');

        if ($request->input('status') !== null) {
            $db = $db->where('w.approved', $request->input('status'));
        }
        $select = [
            'w.*',
            'u.abbr',

            'rm.simplified_chiness_value as rm_name',
            'pm.simplified_chiness_value as pm_name',
            'ct.simplified_chiness_value as ct_name',
            'mm.simplified_chiness_value as make_name',

        ];
        $data = $db->select($select)
            ->orderByDesc('w.id')
            ->limit(3000)
            ->get();
        $wids = Arr::pluck($data, 'id');

        $select = [
            'wvc.roll_number',
            'wvc.warranty_id',
            'wvc.length',
            'wvc.width',
            DB::raw('if(wvc.precut_or_manual=2, "手工", "专车专用") as precuts'),
            'pm.simplified_chiness_value as part_name',
            'fm.simplified_chiness_value as film_name',
        ];

        $tvc = DB::table('warranty_to_vehicle_coverage as wvc')
            ->leftJoin('part_master as pm', 'wvc.part_id', 'pm.id')
            ->leftJoin('film_type_master as fm', 'wvc.film_type_id', 'fm.id')
            ->whereNull('wvc.deleted_at')
            ->whereIn('wvc.warranty_id', $wids)
            ->select($select)
            ->get();
        $wvcs = [];
        foreach ($tvc as $k => $v) {
            $key = $v->warranty_id;
            if (empty($wvcs[$key])) {
                $wvcs[$key] = [];
            }
            $wvcs[$key][] = $v;
        }

        $fields = [
            'warranty_id' => '质保ID',
            'first_name' => '姓名',
            'rm_name' => '区域',
            'pm_name' => '省',
            'ct_name' => '城市',
            'zip' => '邮编',
            'email_address' => '电子邮件',
            'ext_phone' => '电话号码',
            'address' => '地址',
            'year_id' => '年份',
            'make_name' => '品牌',
            'model_name' => '车型',
            'license_plate' => '牌照',
            'vin_number' => '车架号',
            'dealer_name' => '装贴门店',
            'installer_name' => '安装师傅',
            'installation_date' => '安装日期',
            'installation_price' => '安装价格',
            'parts' => '部位',
            'precuts' => '施工类型（裁切或手工）',
            'roll_numbers' => '卷号',
            'lengths' => '使用长度',
            'films' => '膜的种类',
            'widths' => '薄膜宽度',
            'additional_comments' => '补充说明',
        ];

        $uploads = [];
        foreach ($data as $k => $v) {
            $v->model_name = ts('model_master.'.$v->model_id) ?: $v->model_id;
            $v->dealer_name = $v->dealer_name ?: $v->abbr;
            $v->ext_phone = $v->extension . '-' . $v->phone_number;
            $v->installation_date = date('Y-m-d', strtotime($v->installation_date));
            $cov = @$wvcs[$v->id];
            $v->parts = [];
            $v->precuts = [];
            $v->roll_numbers = [];
            $v->films = [];
            $v->widths = [];
            $v->lengths = [];

            if (!empty($cov)) {
                $v->parts = Arr::pluck($cov, 'part_name');
                $v->precuts = Arr::pluck($cov, 'precuts');
                $v->roll_numbers = Arr::pluck($cov, 'roll_number');
                $v->lengths = Arr::pluck($cov, 'length');
                $v->films = Arr::pluck($cov, 'film_name');
                $v->widths = Arr::pluck($cov, 'width');
            }
            $v->parts = implode("\n", $v->parts);
            $v->precuts = implode("\n", $v->precuts);
            $v->roll_numbers = implode("\n", $v->roll_numbers);
            $v->lengths = implode("\n", $v->lengths);
            $v->films = implode("\n", $v->films);
            $v->widths = implode("\n", $v->widths);

            $item = [];
            foreach ($fields as $f=>$m) {
                $item[] = [
                    'label' => $m,
                    'value' => $v->$f
                ];
            }
            $uploads[] = $item;
        }

        return makeExcel($uploads, '质保');
    }

    /*套件批量导入*/
    public function import2(Request $request)
    {
        $page = [
            'page_name' => 'warranty',
            'title' => '套件质保批量导入',
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        return view('admin.warranty.import', [
            'page' => $page,
            'asp'  => 1,
        ]);
    }
    /*套件批量导入*/
    public function handle_import2(Request $request)
    {
        $admin_id = gui();
        $admin_type = gut();


        Log::channel('wlog')->info(json_encode(['质保导入开始']));
        $admin_id = session('admin.id');
        $file = $request->file('file');
        if (empty($file)) {
            return redirect('/warranty/import2')->withInput()->with('trash', ['content'=>'文件不存在！', 'type'=>'error']);
        }
        if ($file->getClientOriginalExtension() != 'xlsx') {
            return redirect('/warranty/import2')->withInput()->with('trash', ['content'=>'仅支持上传xlsx类型文件', 'type'=>'error']);
        }
        $filename = time().Str::random(4) . '.xlsx';
        $path = getFileStorePath(2);
        $bool = $file->storeAs($path['path'], $filename, 'storage');
        $full_file_name = $path['path'].$filename; // /upload/XXX/filename
        $mod = new FileUpload();
        $mod->type = 2;
        $mod->name = '质保文件上传';
        $mod->user_id = $admin_id;
        $mod->file = $full_file_name;
        $mod->save();
        $file = $path['base'] . $filename;

        alogs('质保', '批量导入', $mod->id, ['file'=>$file], null);
        $spreadsheet = IOFactory::load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $raw = $sheet->toArray(null, true, true, true);

        $regions = getRegionList();
        $provinces = getProvinceList();
        $cities = getCityList();

        $makes = getMakeList();
        $models = getModelList();
        if ($admin_type == 2) {
            $abbrs = getUsersList(gui());
            $user = Admin::where('id', $admin_id)->first();
            if (!empty($user)) {
                $abbrs[$user->abbr] = $user['id'];
            }
        } else {
            $abbrs = getUsersList();
        }
        $rpid = Arr::pluck($raw, 'R');
        $pids = getNewPrecutIds($rpid);

        $upload = [];
        $created_by = gui();
        $errors = [];
        foreach ($raw as $k => $v) {
            foreach ($v as $ek=>$ev) {
                $v[$ek] = trim($ev);
            }
            if ($k == 1 && $v['A']=='姓名') {
                continue;
            }
            if (empty($v['A'])) {
                continue;
            }
            $C11 = $v['P'];
            $installation_date = '';
            try {
                if (is_string($C11)) {
                    $C11 = trim($C11);
                    if (mb_strpos($C11, '年')) {
                        $idate_arr = date_parse_from_format('Y年m月d日',$C11);
                        $installation_date = mktime(0,0,0,$idate_arr['month'],$idate_arr['day'],$idate_arr['year']);
                        $installation_date = date('Y-m-d', $installation_date);
                    } else {
                        $installation_date = strtotime($C11);
                        $installation_date = date('Y-m-d', $installation_date);
                    }
                } else {
                    $installation_date = Date::excelToTimestamp($C11);
                    $installation_date = date('Y-m-d', $installation_date);
                }
            } catch (\Exception $exception) {
                $installation_date = null;
            }

            $v['B'] = $v['B'] ?: '中国大陆';
            $region_id = (int) @$regions[$v['B']]; // 地区
            $province_id = (int) @$provinces[$v['C']]; // 地区
            $city = (int) @$cities[$v['D']]; // 地区
            $make_id = (int) @$makes[$v['J']]; // 地区
            $model_id = (int) @$makes[$v['K']]; // 地区
            $user_id = (int) @$abbrs[$v['N']];
            if ($admin_type == 4) {
                $userService = new UserService();
                $distributions = $userService->getDistributions(4, $admin_id);
                $userIdArr = $distributions;
                if (!empty($distributions)) {
                    $dealers = $userService->getDealers($distributions);
                    $userIdArr = array_merge($userIdArr, $dealers);
                }

                if (!empty($userIdArr) && !in_array($user_id, $userIdArr)) {
                    $errors[] = ['msg' => '只能导入自己下属的专车专用套件'];
                }
            }

            $precut_id = 0;
            $precut = @$pids[$v['R']];
            if (!empty($precut)) {
                if ($precut['status']!=1) {
                    if ($precut['user_id']==$user_id) {
                        $precut_id = $precut['id'];
                        $pids[$v['R']]['status'] = 1;
                    } else {
                        $errors[] = ['msg' => $v['R'] . ' 该专车专用套件ID未分配给该门店'];
                    }
                } else {
                    $errors[] = ['msg' => $v['R'] . ' 该专车专用套件ID不可重复安装'];
                }
            } else {
                if (empty($v['R'])) {
                    $errors[] = ['msg' => '专车专用套件ID不能为空'];
                } else {
                    $errors[] = ['msg' => $v['R'] . '专车专用套件ID不存在'];
                }

            }
            $installation_images = [];
            if (!empty($v['T'])) {
                $installation_images_zip_url = $spreadsheet->getActiveSheet()->getCell('T'.$k)->getHyperlink()->getUrl(); // 安装图片地址
                $installation_images = $this->getInstalationImagesByZipUrl($installation_images_zip_url);
            }
            $upload[] = [
                'first_name' => $v['A'],
                'region_id' => $region_id,
                'province_id' => $province_id,
                'city' => $city,
                'zip' => $v['E'],
                'email_address' => $v['F'],
                'phone_number' => $v['G'],
                'address' => $v['H'],
                'year_id' => $v['I'],
                'make_id' => $make_id,
                'model_id' => $model_id,
                'license_plate' => $v['L'],
                'vin_number' => $v['M'],
                'user_id' => $user_id, // 经销商ID
                'installer_name' => $v['O'],
                'installation_price' => $v['Q'],
                'installation_date' => $installation_date,
                'precut_id' => $precut_id,
                'additional_comments' => $v['S'],
                'created_by' => $created_by,
                'approved' => 3,
                'images' => $installation_images,
            ];
        }

        if (empty($upload)) {
            return back()->with('uploadError', ['msg' => '导入数据为空！']);
        }
        if (!empty($errors)) {
            return back()->with('uploadError', $errors);
        }
        foreach ($upload as $k => $v) {
            $model = new Warranty();
            foreach ($v as $ek => $ev) {
                if ('images' == $ek) {
                    continue;
                }
                $model->$ek = $ev;
            }
            $model->warranty_id = makeWarrantyId();
            $model->save();
            $rmg = $v['images'] ?? [];
            $imgs = [];
            foreach ($rmg as $imgK => $imgV) {
                $item = [];
                $item['warranty_id'] = $model->id;
                $item['created_at'] = gDate();
                $item['updated_at'] = gDate();
                $item['image_src'] = $imgV;
                $item['part_id'] = $imgK+1;
                $imgs[] = $item;
            }
            if (!empty($imgs)) {
                DB::table('warranty_image')->insert($imgs);
//                if (count($imgs) < 6 || count($imgs) > 12) {
//                    $msg[] = "安装图片保证清晰且最多12张，最少6张；";
//                }
            }
            if ($model->precut_id) {
                $pre = NewPrecut::find($model->precut_id);
                $pre->status = 1;
                $pre->save();
            }
        }
        return redirect('/admin/warranty')->with('trash', '批量上传成功！');
    }

    public function create2(Request $request)
    {
        $user_type = session('admin.user_type');
        $unique_id = session('admin.unique_id');
        Refresh();
        if (session('admin.warranty_create') != 1) {
            return abort(404);
        }
        $page = [
            'page_name' => 'warranty',
            'title' => ts('ADDWARENTY'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        $data = new Warranty();
        return view('admin.warranty.create2', [
            'data'=>$data,
            'page' => $page,
        ]);
    }

    public function aspImport(Request $request)
    {
        $page = [
            'page_name' => 'asp_warranty',
            'title' => 'ASP批量导入',
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];
        return view('admin.warranty.asp_import', ['page' => $page]);
    }

    public function handleAspImport(Request $request)
    {
        (new WarrantyService())->importData($request);
    }
}
